package org.eclipse.rally.plugin.views;

import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import org.apache.axis.client.Stub;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.rally.plugin.utils.RallyConstants;
import org.eclipse.rally.plugin.utils.SWTResourceManager;
import org.eclipse.rally.plugin.webservice.RallyMain;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

import com.rallydev.webservice.v1_12.domain.Defect;
import com.rallydev.webservice.v1_12.domain.HierarchicalRequirement;
import com.rallydev.webservice.v1_12.domain.Task;


public class HeaderPage extends ApplicationWindow {
    public static String userNameFromRally = "";
    public static String userEmailFromRally = "";
    public static HeaderPage loginWindow;
    TabFolder tabFolder;
    public static TabItem tabItem;
    Shell shell = new Shell(Display.getCurrent(), SWT.NO_TRIM);
    Composite composite;
    ViewPart rallyViewPart;
    public static Text searchtext;
    static Map refTaskMap;
    HeaderPage(ViewPart viewPart) {
        super(null);
        this.rallyViewPart = viewPart;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        loginWindow = new HeaderPage(null);
        loginWindow.setShellStyle(SWT.NONE);
        loginWindow.setBlockOnOpen(true);
        loginWindow.open();
        Display.getCurrent().dispose();
    }

    public Control createContents(final Composite parent) {
        parent.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_WIDGET_LIGHT_SHADOW));

        composite = new Composite(parent, SWT.NONE);
        composite.setBounds(0, 0, 938, 35);
        composite.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_LIST_BACKGROUND));
        composite.setLayout(null);

        final CLabel clbl_Username = new CLabel(composite, SWT.NONE);
        clbl_Username.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_LIST_BACKGROUND));

       
        final CLabel clbl_UserLogin = new CLabel(composite, SWT.NONE);
        clbl_UserLogin.setText("Rally");
        clbl_UserLogin.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_LIST_BACKGROUND));
        clbl_UserLogin.setImage(SWTResourceManager.getImage(HeaderPage.class,
                "/icons/icon-rally.gif"));

        clbl_UserLogin.setBounds(0, 0, 90, 30);

        Font font = new Font(composite.getDisplay(), "Arial Black", 12,
                SWT.NORMAL);

        clbl_UserLogin.setFont(font);

        clbl_Username.setBounds(290, 6, 117, 15);
        clbl_Username.setText("Welcome :" + userNameFromRally);

       
        String message = "<a>Logout</a>";

        Link link = new Link(composite, SWT.NONE);
        link.setText(message);
        link.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_LIST_BACKGROUND));
        //logout.setFont(font);
        link.setBounds(895,6, 40, 20);
        link.addListener(SWT.Selection,
            new Listener() {
                public void handleEvent(Event event) {
                    MessageBox messageBox = new MessageBox(new Shell(
                                Display.getCurrent()),
                            SWT.ICON_QUESTION | SWT.YES | SWT.NO);
                    messageBox.setMessage("Do you really want to exit?");
                    messageBox.setText("Logout Rally");

                    int response = messageBox.open();
                    System.out.println("Response: " + response);

                    if (response == SWT.YES) {
                        if (RallyMain.getService() != null) {
                            Stub stub = (Stub) RallyMain.getService();
                            stub.setMaintainSession(false);
                            closeRallyView();
                        }
                    }
                }
            });

        Label label_1 = new Label(composite, SWT.NONE);
        label_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
        label_1.setBounds(0, 30, 1050, 2);

        Label label_2 = new Label(composite, SWT.NONE);
        label_2.setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE));
        label_2.setBounds(0, 33, 1050, 2);
        {
        	searchtext = new Text(composite, SWT.BORDER);
        	searchtext.setBounds(600, 6, 100, 19);
        }
        {
        	final Label searchlabel = new Label(composite, SWT.NONE);
        	searchlabel.setImage(SWTResourceManager.getImage(HeaderPage.class, "/icons/Search-enabled.gif"));
        	searchlabel.setBackground(SWTResourceManager.getColor(255, 255, 255));
        	searchlabel.setBounds(710, 6, 60, 20);
        	
        	searchlabel.addMouseTrackListener(new MouseTrackAdapter() {
       			@Override
       			public void mouseHover(MouseEvent e) {
       				final Cursor cursor = new Cursor(Display.getCurrent(),
       						SWT.CURSOR_HAND);
       
       				searchlabel.setCursor(cursor);
       
       			}
       		});
        	searchlabel.addMouseListener(new MouseAdapter() {
               			@Override
               			public void mouseDown(MouseEvent e) {
               			
               				if(searchtext.getText()=="")
               				{
               				JOptionPane.showMessageDialog(null,"Search Value is Required", "", 0);	
               				}
               				else
               					{globalRallySearch();}
               			
               			 }
                              
               		});
        	
        }
        
        return composite;
    }
private static String defectglobalSearch(String searchString){
	    String defectRef = null;
	    if(searchString != null){
	    	 try{
	    Defect defect = new Defect();
	                 defect.setFormattedID(searchString);
	                 RallyMain rallyMain = new RallyMain();
	                List searchDefect = rallyMain.searchObject(defect, "Defect");
	                if(searchDefect.size() > 0){
	                Defect def = (Defect)searchDefect.get(0);
	                defectRef = def.getRef();
	                } else
	        	    {
	        	    	JOptionPane.showMessageDialog(null,"There are no results to display.", "", 0);		
	        	    }
	    	 }catch(Exception e)
	    	   {
	    		   System.out.println("Not a Proper Value" +searchString);
	    	   }  
	  
	    }
	   
	    return defectRef;
	    }
static String taskglobalSearch(String searchString){
    String defectRef = null;
    if(searchString != null){
   try{
    Task task = new Task();
    	task.setFormattedID(searchString);
                 RallyMain rallyMain = new RallyMain();
                List searchDefect = rallyMain.searchObject(task, "Task");
                if(searchDefect.size() > 0){
                Task def = (Task)searchDefect.get(0);
                defectRef = def.getRef();
                }
             
   }catch(Exception e)
   {
	   System.out.println("Not a Proper Value" +searchString);
   }
  
    }
    
    return defectRef;
    }   
static String userStoryGlobalSearch(String searchString){
    String userstoryRef = null;
    if(searchString != null){
   
    	HierarchicalRequirement userstory = new HierarchicalRequirement();
    	userstory.setFormattedID(searchString);
                 RallyMain rallyMain = new RallyMain();
                List searchuserstory = rallyMain.searchObject(userstory, "HierarchicalRequirement");
                if(searchuserstory.size() > 0){
                HierarchicalRequirement def = (HierarchicalRequirement)searchuserstory.get(0);
                userstoryRef = def.getRef();
                }
    }
    return userstoryRef;
    }

public  TabFolder getTabFolder() {
	return tabFolder;
}

public  void setTabFolder(TabFolder tabFolder_1) {
	tabFolder = tabFolder_1;
}

/*public TabFolder tabName(TabFolder tabFolder_1)
{
	 tabFolder=tabFolder_1;
	return tabFolder;
}*/
 public void globalRallySearch()	
{
	
	 String input=searchtext.getText();

	 TabItem tabItems[]=getTabFolder().getItems();
	 
	
	 if(input.toUpperCase().startsWith("DE"))
	 {
			 tabItem=tabItems[1];
			 	
	 System.out.println("tabItem_1"+tabItems[1] +"tabItem_2"+tabItems[2] +"tabItem_3"+tabItems[3]);
	 String defectRef = defectglobalSearch(input);
	 if(defectRef != null){
	    new DefectDetailGUI().defectDetail(tabFolder,tabItem,  defectRef, RallyConstants.PAGE_DEFECTS);
	 tabFolder.setSelection(tabItem);
	 System.out.println("Inside Defect Page Value of item here :  "+tabItem+1);
	 }
	}
	else if(input.toUpperCase().startsWith("TA"))
	{
		
	
		tabItem=tabItems[3];
		String taskRef = taskglobalSearch(input);
		if(taskRef != null){
		  new TaskDetailGUI().taskDetail(tabFolder,tabItem, taskRef,"Task");
		  tabFolder.setSelection(tabItem);
		System.out.println("Task Detail Page");
		}
	}
	else if(input.toUpperCase().startsWith("US"))
	{
		tabItem=tabItems[2];
		String user_story=userStoryGlobalSearch(input);
		if(user_story != null){
			new UserStoryDetailGUI().userStoryDetail(tabFolder, tabItem,user_story, RallyConstants.PAGE_USERSTORIES);
			  tabFolder.setSelection(tabItem);
			System.out.println("User Story Details Page");
			}
		
	}else{
		JOptionPane.showMessageDialog(null,"There are no results to display.", "", 0);
		
	}
	
	}

    public void closeRallyView() {
        final IWorkbenchWindow[] windows = PlatformUI.getWorkbench()
                                                     .getWorkbenchWindows();

       
        for (int w = 0; w < windows.length; w++) {
            final IWorkbenchPage[] pages = windows[w].getPages();

            // for all workbench pages of a given workbench window
            for (int p = 0; p < pages.length; p++) {
                final IWorkbenchPage page = pages[p];
                final IViewReference[] viewRefs = page.getViewReferences();

                // for all view references of a given workbench page of a given workbench window
                for (int v = 0; v < viewRefs.length; v++) {
                    final IViewReference viewRef = viewRefs[v];
                    final IWorkbenchPart viewPart = viewRef.getPart(false);
                    Class partType = null;

                    if (viewPart != null) {
                        partType = viewPart.getClass();

                        if ((rallyViewPart == null) ||
                                rallyViewPart.getClass().equals(partType)) {
                            page.hideView(viewRef);
                        }
                    }
                }
            }
        }
    }
}
